﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using LinqKit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using QualitySupervision.Core;
using QualitySupervision.Models;
using QualitySupervision.Utility;

namespace QualitySupervision.Controllers
{
    //[Route("api/[controller]")]
    [Route("api/")]
    [ApiController]
    //[Authorize]
    public class AllController : Controller
    {
        private readonly ApiDBContent _dbContext;

        public AllController(ApiDBContent dbContext)
        //public AllController(ApiDBContent dbContext, IConfiguration configuration)
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="rid">权限等级</param>
        /// <returns></returns>
        [HttpGet("menus")]
        public IActionResult Menus([FromQuery] string rid)
        {
            var meta = new
            {
                msg = "获取菜单列表成功",
                status = 200
            };
            var meta2 = new
            {
                msg = "没有该角色的权限",
                status = 404
            };
            var data = _dbContext.Menus.OrderBy(o => o.order).Include("children").ToList();
            //.Where(x => x.rid.Contains(rid)).OrderBy(o => o.order)
            //查询出该角色所有的权限
            var data2 = _dbContext.roles.Find(int.Parse(rid));
            if (data2 == null)
            {
                return Json(new { meta2 });
            }

            
            string[] ids = data2.rightid.Split(",");
            //定义一个长度和字符串数组一样的int数组
            int[] idss = new int[data2.rightid.Split(",").Count()];
            //权限列表信息
            Right Rightsinfo = new Right();
            //权限名称列表信息
            List<string> RightsNameInfo = new List<string>();
            //所有权限对象
            //List<Right> Rightlist = new List<Right>();
            //for循环字符串数组
            for (int i = 0; i < data2.rightid.Split(",").Count(); i++)
            {
                // 将字符串数组转换成int数组
                idss[i] = Convert.ToInt32(ids[i]);
                //查询出id对应的权限信息赋值给Rightsinfo
                Rightsinfo = _dbContext.Rights.Find(idss[i]);
                //.Where(w => w.id == int.Parse(item.rightid.Split(",")[i]))
                //.Where(w => w.id == idss[i]).;
                //Rightlist.Add(Rightsinfo);
                //只取1级菜单名称
                if (Rightsinfo.level == "0")
                {
                    //一级菜单名称，添加到权限名称列表里
                    RightsNameInfo.Add(Rightsinfo.authName);
                } 
            }
            //一级菜单对象List
            List<Menu> Menutlist = new List<Menu>();
            Menu Menuinfo = new Menu();
            foreach (var item in RightsNameInfo)
            {
                //一级菜单对象List赋值
                Menuinfo = _dbContext.Menus.Single(x => x.authName == item);
                Menutlist.Add(Menuinfo);
                //Menuinfo = null;
            }

            return Json(new { meta, data = Menutlist });
        }

        /// <summary>
        /// 页面权限
        /// </summary>
        /// <param name="path">路径名称</param>
        /// <param name="rid">角色id</param>
        /// <returns></returns>
        [HttpGet("menuright")]
        public IActionResult GetMenuRight([FromQuery] string path, string rid)
        {
            var meta = new
            {
                msg = "您有该页面访问权限",
                status = 200
            };
            var meta2 = new
            {
                msg = "您无权访问该页面",
                status = 404
            };

            //var data = _dbContext.Menus.OrderBy(o => o.order).Include("children").ToList();
            //查询出该角色所有的权限id字符串
            var rightidstr = _dbContext.roles.Find(int.Parse(rid));
            List<string> Rightidlist = new List<string>();
            //将权限id字符串分割生成列表存到rightidlist里
            Rightidlist = rightidstr.rightid.Split(",").ToList();

            List<Right> rightlist = new List<Right>();
            foreach (var item in Rightidlist)
            {
                //var right = _dbContext.Rights.Single(w => w.level == "1" && w.id == int.Parse(item));
                var right = _dbContext.Rights.Find(int.Parse(item));
                if (right.level == "1")
                {
                    rightlist.Add(right);
                }
                
            }
            bool isright = false;
            string Rightpath = null;
            //单个2级权限
            Right Right2ji = new Right();
            //3级权限列表
            List<Right> Right3ji = new List<Right>();
            foreach (var item in rightlist)
            {
                //如果完整路径包含数据库里权限的路径
                if (path.Contains(item.path))
                {
                    isright = true;
                    Rightpath = item.path;
                    Right2ji = _dbContext.Rights.Single(w => w.level == "1" && w.path == Rightpath);
                    Right3ji = _dbContext.Rights.Where(w => w.level == "2" && w.pid == Right2ji.id).ToList();
                }
            }
            //var Right2ji = _dbContext.Rights.Single(w => w.level == "1" && w.path == Rightpath);
            //var Right3ji = _dbContext.Rights.Where(w => w.level == "2" && w.pid == Right2ji.id);

            if (isright)
            {
                return Json(new { meta, rightlist, Right3ji });
            }
            else
            {
                return Json(new { meta=meta2, rightlist, Right3ji });
            }
            
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="query">用户名称</param>
        /// <param name="pagenum">当前页数</param>
        /// <param name="pageSize">当前页码</param>
        /// <returns></returns>
        //[HttpGet("menus")]
        //public IActionResult users()
        //{
        //    var meta = new
        //    {
        //        msg = "获取菜单列表成功",
        //        status = 200
        //    };
        //    var data = _dbContext.Users.ToList();
        //    //var data2 = _dbContext.Menus
        //    //    .Include(x=>x.children)
        //    //    .ToList();
        //    return Json(new { meta = meta, data = data });
        //}
        [HttpGet("users")]
        public async Task<IActionResult> Getusers([FromQuery] string query, int pagenum = 1, int pageSize = 20)
        {
            //方法二：Using PredicateBuilder
            //LinqKit.Microsoft.EntityFrameworkCore
            //https://github.com/scottksmith95/LINQKit
            var predicate = PredicateBuilder.New<User>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            if (!string.IsNullOrEmpty(query))
            {
                predicate = predicate.And(p => p.username.Contains(query));
            }

            var users = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID);

            var data = await PaginatedList<User>.CreatePagingAsync(users, pagenum, pageSize);
            var meta = new
            {
                msg = "获取用户列表成功",
                status = 200
            };
            return Json(new { meta, data });
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("users")]
        public async Task<IActionResult> Adduser([FromBody] User user)
        {
            //方法二：Using PredicateBuilder
            //LinqKit.Microsoft.EntityFrameworkCore
            //https://github.com/scottksmith95/LINQKit
            var predicate = PredicateBuilder.New<User>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            if (!string.IsNullOrEmpty(user.username))
            {
                predicate = predicate.And(p => p.username==user.username);
            }
            var count = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID).Count();
            //var data = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID).ToList();
            //var data = PaginatedList<User>.CreatePagingAsync(users, pageIndex, pageSize);
            //var data = _dbContext.Menus.ToList();
            
            var meta = new { msg = "用户添加成功", status = 201 };
            var meta2 = new { msg = "用户名已存在", status = 401 };
            if (count == 1)
            {
                return Json(new { meta = meta2 });
            }
            else
            {
                _dbContext.Users.Add(user);
                await _dbContext.SaveChangesAsync();
                return Json(new { meta,data = user });
            };
        }
        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        [HttpGet("users/{id}")]
        public async Task<ActionResult> GetUserInfo(int id)
        {
            var userInfo = await _dbContext.Users.FindAsync(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (userInfo == null)
            {
                return Json(new { meta = meta2 });
            }
            var meta = new
            {
                msg = "用户查询成功",
                status = 200
            };
            return Json(new { meta,data= userInfo });
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="user">特别注意:不需要更新的字段一定要传递为NULL</param>
        /// <returns></returns>
        [HttpPut("users/{id}")]
        public async Task<ActionResult> PutUserInfo(int id, [FromBody] User user)
        {
            var existInfo = _dbContext.Users.Find(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}记录" });
            }
            //existInfo.username = user.username ?? existInfo.username;
            existInfo.mobile = user.mobile ?? existInfo.mobile;
            existInfo.email = user.email ?? existInfo.email;
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "用户修改成功",
                status = 200
            };
            return Json(new { meta, data = existInfo });
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPut("editpassword")]
        public async Task<ActionResult> PutEditPassword(string username, string password)
        {
            var userInfo = _dbContext.Users.Single(w =>w.username == username);
            var meta2 = new
            {
                msg = "修改密码与原来密码一样",
                status = 404
            };
            if (userInfo.password == password)
            {
                return Json(new { meta = meta2, msg = "密码修改失败" });
            }

            //existInfo.username = user.username ?? existInfo.username;
            //userInfo.mobile = user.mobile ?? existInfo.mobile;
            //existInfo.email = user.email ?? existInfo.email;
            userInfo.password = password;
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "密码修改成功",
                status = 200
            };
            return Json(new { meta, data = userInfo });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        [HttpDelete("users/{id}")]
        public async Task<ActionResult> DeleteUser(int id)
        {
            var existUser = _dbContext.Users.Find(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existUser == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}记录" });
            }
            //var user = new User() { ID = id };
            _dbContext.Remove(existUser);
            await _dbContext.SaveChangesAsync();

            var meta = new
            {
                msg = "用户删除成功",
                status = 200
            };
            return Json(new { meta });
        }
        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="state">用户状态</param>
        /// <returns></returns>
        [HttpPut("users/{id}/state/{state}")]
        public async Task<ActionResult> PutUserState(int id, bool state)
        {
            var existInfo = _dbContext.Users.Find(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}记录" });
            }
            //existInfo.username = user.username ?? existInfo.username;
            if (state)
            {
                existInfo.mg_state = true;
            }
            else
            {
                existInfo.mg_state = false;
            }
            
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "用户状态修改成功",
                status = 200
            };
            return Json(new { meta, data = existInfo });
        }
        /// <summary>
        /// 获取项目信息列表
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="area">区域</param>
        /// <param name="projectname">项目名称</param>
        /// <param name="serialno">项目编号</param>
        /// <param name="mobileprojectno">项目编号</param>
        /// <param name="pagenum">当前页数</param>
        /// <param name="pageSize">当前页码</param>
        /// <returns></returns>
        [HttpGet("projectinfo")]
        //public async Task<IActionResult> GetProjectInfo([FromQuery] int year, string serialno, int pagenum = 1, int pageSize = 20)
        public async Task<IActionResult> GetProjectInfo([FromQuery] string year, string area, string projectname, string serialno, string mobileprojectno, int pagenum = 1, int pageSize = 10)
        {

            //方法二：Using PredicateBuilder
            //LinqKit.Microsoft.EntityFrameworkCore
            //https://github.com/scottksmith95/LINQKit

            var predicate = PredicateBuilder.New<Project>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            if (!string.IsNullOrEmpty(year))
            {
                predicate = predicate.And(p => p.Year==int.Parse(year));
            }
            if (!string.IsNullOrEmpty(area))
            {
                predicate = predicate.And(p => p.Area == area);
            }
            if (!string.IsNullOrEmpty(projectname))
            {
                predicate = predicate.And(p => p.ProjectName.Contains(projectname));
            }
            if (!string.IsNullOrEmpty(serialno))
            {
                predicate = predicate.And(p => p.SerialNo.Contains(serialno));
            }
            if (!string.IsNullOrEmpty(mobileprojectno))
            {
                predicate = predicate.And(p => p.MobileProjectNo.Contains(mobileprojectno));
            }
            //var info = _dbContext.StrategicTargetTasks.Where(predicate).Select(s => s).OrderBy(o => o.ID).Include(a => a.AppraiseUnits).ThenInclude( b=> new {
            //    b.Dept,
            //    b.Deptmentname,
            //    b.Grade,
            //    b.Gradeself,
            //    b.State,
            //    b.Rank
            //});
            //var info = _dbContext.StrategicTargetTasks.Where(predicate).Select(s => s).OrderBy(o => o.ID).Include(a => a.AppraiseUnits);

            //var info = _dbContext.StrategicTargetTasks.Where(predicate).OrderBy(o => o.ID).Select(s => new { 
            //    s.ID,
            //    s.Title,
            //    s.CreateTime,
            //    s.AppraiseUnits
            //});
            //IQueryable<Project> info2 = new IQueryable<Project>();
            //List<Project> info = new List<Project>();
            var info = _dbContext.Projects.Where(predicate).OrderByDescending(o => o.ID).Include("Fujians");
            //var info = _dbContext.Projects.Where(predicate).Select(s => new
            //{
            //    s.ID,
            //    s.Year,
            //    s.SerialNo,
            //    s.Area,
            //    s.ProjectName,
            //    s.EntrustMoney,
            //    s.CostMoney,
            //    s.PriceExcludingTax,
            //    s.SettlementMoney,
            //    s.SettlementMoneyExcludingTax,
            //    s.MarkUpRate,
            //    s.EntrustTime,
            //    s.InquiryTime,
            //    s.ContractSignTime,
            //    s.FinalInspectionTime,
            //    s.SettlementTime,
            //    s.MaintenanceCycle,
            //    s.MobileProjectNo,
            //    s.ProjectManager,
            //    s.ServiceManager,
            //    s.CurrentStage,
            //    s.Zhousanbeizhu,
            //    s.Supplier,
            //    s.Contacts,
            //    s.IsFinish,
            //    s.IsMaintain,
            //    s.Beizhu,
            //    s.Income,
            //    s.ActuallyIncome,
            //    s.IncomeTime,
            //    s.OwnerAcceptanceTime,
            //    s.CreateTime,
            //    s.Fujians
            //}).OrderByDescending(o => o.ID).Include("Fujians");
            //List<Project> info2 = new List<Project>();
            //var info2 = info.Select(s => new { s.ID, s.Year, s.Area, s.CreateTime });
            var data = await PaginatedList<Project>.CreatePagingAsync(info, pagenum, pageSize);
            //var data = await PaginatedList<Project>.CreatePagingAsync((IQueryable<Project>)info, pagenum, pageSize);
            var meta = new
            {
                msg = "获取项目信息列表成功",
                status = 200
            };
            return Json(new { meta, data });
        }

        /// <summary>
        /// 导入项目信息比对
        /// </summary>
        [HttpGet("projects")]
        public async Task<IActionResult> Getprojects()
        {
            var meta = new
            {
                msg = "获取项目列表成功",
                status = 200
            };
            var data = await _dbContext.Projects.Select(s => new {
                s.SerialNo,
                s.Area,//区县
                s.ProjectName,//项目名称
                s.SettlementMoney,//预算含税总额(元)(含加成)(结算金额)
                s.SettlementMoneyExcludingTax,
                s.MobileProjectNo,//ICT编号
                s.ProjectManager,//母公司项目经理
                s.ServiceManager,//服务经理
                s.EntrustTime,//委托完成日期
                //s.Income,
                //s.ActuallyIncome,
                //s.IncomeTime,
                //s.OwnerAcceptanceTime,
                s.Sfjs,
                s.Sfzt,
                s.Qqjcgszc,
                s.Sffb,
                s.Xmbh,
                s.Qy,
                s.Nlbm,
                s.Jsfs,
                s.Swhzms,
                s.Sfxmsj,
                s.Sfcgkjht,
                s.SfnrPMOgl,
                s.Jsms,
                s.Zcms,
                s.Sfwg,
                s.Sfcwg,
                s.Ywjcje,
                s.Cpyfje,
                s.Cpzcje,
                s.Ptszyy,
                s.Zbje,
                s.Htqyje,
                s.Ylxsrje,
                s.Ylxcbje,
                s.Wtrq,
                s.Zbrq,
                s.Zbwtsc,
                s.Yjhy,
                s.Erhy,
                s.Xmfl,
                s.Xmlx,
                s.Zdssn,
                s.Zdssw,
                s.Ctph,
                s.Xmjd,
                s.Ctjd,
                s.Ctyit,
                s.Zhyy,
                s.Yqzysj,
                s.Xmtdzjrq,
                s.Qdsj,
                s.Ssfaxttjsj,
                s.Ssfatjsj,
                s.Ssfaqrsj,
                s.Jhkgsj,
                s.Kgyqts,
                s.Sjkgsj,
                s.Dyccgwcsj,
                s.Cgwcsj,
                s.Jhdhsj,
                s.Dhsj,
                s.Xmjdsj,
                s.Xmjdhysj,
                s.Jhsxsj,
                s.Sxqyts,
                s.Sjsxsj,
                s.Yzcysj,
                s.Mgssjcysj,
                s.Yzzysj,
                s.Mgsjhzysj,
                s.Zyyqts,
                s.Mgssjzysj,
                s.Jhzwsj,
                s.Zwwcsj,
                s.Gxsj,
                s.Sfyxmsjjdpp,
                s.Bz,
                s.Jcgsjsdw,
                s.Xqhtlxkssj,
                s.Xqhtlxjssj,
                s.Zwzt,
                s.Whjssj,
                s.Whzt,
                s.Whlx,
                s.Whzq,
                s.Zbzq
            }).ToListAsync();
            //var data2 = _dbContext.Menus
            //    .Include(x=>x.children)
            //    .ToList();
            return Json(new { meta, data });
        }

        /// <summary>
        /// 所有工程项目的移动项目编号
        /// </summary>
        [HttpGet("mobileprojectno")]
        public async Task<IActionResult> Getmobileprojectno()
        {
            var meta = new
            {
                msg = "获取工程项目的移动项目编号成功",
                status = 200
            };
            var data = await _dbContext.Projects.Select( s=> s.MobileProjectNo).ToListAsync();
            return Json(new { meta, data });
        }

        /// <summary>
        /// 导入合同信息比对
        /// </summary>
        [HttpGet("contractslist")]
        public async Task<IActionResult> Getcontracts()
        {
            var meta = new
            {
                msg = "获取合同列表成功",
                status = 200
            };
            var data = await _dbContext.Contracts.ToListAsync();
            return Json(new { meta, data });
        }

        /// <summary>
        /// 读取合同类目名称比对信息
        /// </summary>
        [HttpGet("contractskindnamelist")]
        public async Task<IActionResult> Getcontractskindname()
        {
            var meta = new
            {
                msg = "获取合同类别名称列表成功",
                status = 200
            };
            var data = await _dbContext.ProjectKindNames.ToListAsync();
            return Json(new { meta, data });
        }

        /// <summary>
        /// 批量添加工程项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("addprojects")]
        public IActionResult AddProjects([FromBody] List<Project> projects)
        //public async Task<IActionResult> AddProjects([FromBody] List<Project> projects)
        {
            //要添加的数据列表
            List<Project> addinfos = new List<Project>();
            List<Project> editinfos = new List<Project>();
            foreach (var project in projects)
            {
                var Info = _dbContext.Projects.Where(s => s.MobileProjectNo == project.MobileProjectNo).FirstOrDefault();
                if (Info == null)
                {
                    addinfos.Add(project);
                }
                else
                {
                    Info.ProjectName = project.ProjectName ?? Info.ProjectName;
                    Info.Area = project.Area ?? Info.Area;
                    //Info.SettlementMoney = project.SettlementMoney ?? Info.SettlementMoney;
                    //if (Info.SettlementMoney != project.SettlementMoney)
                    //{
                    //    Info.SettlementMoney = project.SettlementMoney;
                    //}
                    Info.ProjectManager = project.ProjectManager ?? Info.ProjectManager;
                    Info.ServiceManager = project.ServiceManager ?? Info.ServiceManager;
                    //---------------
                    Info.Bz = project.Bz ?? Info.Bz;
                    Info.Sfjs = project.Sfjs ?? Info.Sfjs;
                    Info.Sfzt = project.Sfzt ?? Info.Sfzt;
                    Info.Qqjcgszc = project.Qqjcgszc ?? Info.Qqjcgszc;
                    Info.Sffb = project.Sffb ?? Info.Sffb;
                    Info.Xmbh = project.Xmbh ?? Info.Xmbh;
                    Info.Qy = project.Qy ?? Info.Qy;
                    Info.Nlbm = project.Nlbm ?? Info.Nlbm;
                    Info.Jsfs = project.Jsfs ?? Info.Jsfs;
                    Info.Swhzms = project.Swhzms ?? Info.Swhzms;
                    Info.Sfxmsj = project.Sfxmsj ?? Info.Sfxmsj;
                    Info.Sfcgkjht = project.Sfcgkjht ?? Info.Sfcgkjht;
                    Info.SfnrPMOgl = project.SfnrPMOgl ?? Info.SfnrPMOgl;
                    Info.Jsms = project.Jsms ?? Info.Jsms;
                    Info.Zcms = project.Zcms ?? Info.Zcms;
                    Info.Sfwg = project.Sfwg ?? Info.Sfwg;
                    Info.Sfcwg = project.Sfcwg ?? Info.Sfcwg;
                    Info.Ywjcje = project.Ywjcje ?? Info.Ywjcje;
                    Info.Cpyfje = project.Cpyfje ?? Info.Cpyfje;
                    Info.Cpzcje = project.Cpzcje ?? Info.Cpzcje;
                    Info.Ptszyy = project.Ptszyy ?? Info.Ptszyy;
                    Info.Zbje = project.Zbje ?? Info.Zbje;
                    Info.Htqyje = project.Htqyje ?? Info.Htqyje;
                    Info.Ylxsrje = project.Ylxsrje ?? Info.Ylxsrje;
                    Info.Ylxcbje = project.Ylxcbje ?? Info.Ylxcbje;
                    Info.Wtrq = project.Wtrq ?? Info.Wtrq;
                    Info.Zbrq = project.Zbrq ?? Info.Zbrq;
                    Info.Zbwtsc = project.Zbwtsc ?? Info.Zbwtsc;
                    Info.Yjhy = project.Yjhy ?? Info.Yjhy;
                    Info.Erhy = project.Erhy ?? Info.Erhy;
                    Info.Xmfl = project.Xmfl ?? Info.Xmfl;
                    Info.Xmlx = project.Xmlx ?? Info.Xmlx;
                    Info.Zdssn = project.Zdssn ?? Info.Zdssn;
                    Info.Zdssw = project.Zdssw ?? Info.Zdssw;
                    Info.Ctph = project.Ctph ?? Info.Ctph;
                    Info.Xmjd = project.Xmjd ?? Info.Xmjd;
                    Info.Ctjd = project.Ctjd ?? Info.Ctjd;
                    Info.Ctyit = project.Ctyit ?? Info.Ctyit;
                    Info.Zhyy = project.Zhyy ?? Info.Zhyy;
                    Info.Yqzysj = project.Yqzysj ?? Info.Yqzysj;
                    Info.Xmtdzjrq = project.Xmtdzjrq ?? Info.Xmtdzjrq;
                    Info.Qdsj = project.Qdsj ?? Info.Qdsj;
                    Info.Ssfaxttjsj = project.Ssfaxttjsj ?? Info.Ssfaxttjsj;
                    Info.Ssfatjsj = project.Ssfatjsj ?? Info.Ssfatjsj;
                    Info.Ssfaqrsj = project.Ssfaqrsj ?? Info.Ssfaqrsj;
                    Info.Jhkgsj = project.Jhkgsj ?? Info.Jhkgsj;
                    Info.Kgyqts = project.Kgyqts ?? Info.Kgyqts;
                    Info.Sjkgsj = project.Sjkgsj ?? Info.Sjkgsj;
                    Info.Dyccgwcsj = project.Dyccgwcsj ?? Info.Dyccgwcsj;
                    Info.Cgwcsj = project.Cgwcsj ?? Info.Cgwcsj;
                    Info.Jhdhsj = project.Jhdhsj ?? Info.Jhdhsj;
                    Info.Dhsj = project.Dhsj ?? Info.Dhsj;
                    Info.Xmjdsj = project.Xmjdsj ?? Info.Xmjdsj;
                    Info.Xmjdhysj = project.Xmjdhysj ?? Info.Xmjdhysj;
                    Info.Jhsxsj = project.Jhsxsj ?? Info.Jhsxsj;
                    Info.Sxqyts = project.Sxqyts ?? Info.Sxqyts;
                    Info.Sjsxsj = project.Sjsxsj ?? Info.Sjsxsj;
                    Info.Mgssjcysj = project.Mgssjcysj ?? Info.Mgssjcysj;
                    Info.Yzzysj = project.Yzzysj ?? Info.Yzzysj;
                    Info.Mgsjhzysj = project.Mgsjhzysj ?? Info.Mgsjhzysj;
                    Info.Zyyqts = project.Zyyqts ?? Info.Zyyqts;
                    Info.Mgssjzysj = project.Mgssjzysj ?? Info.Mgssjzysj;
                    Info.Jhzwsj = project.Jhzwsj ?? Info.Jhzwsj;
                    Info.Zwwcsj = project.Zwwcsj ?? Info.Zwwcsj;
                    Info.Gxsj = project.Gxsj ?? Info.Gxsj;
                    Info.Sfyxmsjjdpp = project.Sfyxmsjjdpp ?? Info.Sfyxmsjjdpp;
                    Info.Jcgsjsdw = project.Jcgsjsdw ?? Info.Jcgsjsdw;
                    Info.Xqhtlxkssj = project.Xqhtlxkssj ?? Info.Xqhtlxkssj;
                    Info.Xqhtlxjssj = project.Xqhtlxjssj ?? Info.Xqhtlxjssj;
                    Info.Zwzt = project.Zwzt ?? Info.Zwzt;
                    Info.Whjssj = project.Whjssj ?? Info.Whjssj;
                    Info.Whzt = project.Whzt ?? Info.Whzt;
                    Info.Whlx = project.Whlx ?? Info.Whlx;
                    Info.Whzq = project.Whzq ?? Info.Whzq;
                    Info.Zbzq = project.Zbzq ?? Info.Zbzq;
                    Info.BudgetAmount = project.BudgetAmount ?? Info.BudgetAmount;
                    Info.Xmjl = project.Xmjl ?? Info.Xmjl;
                    Info.Yzcysj = project.Yzcysj ?? Info.Yzcysj;
                    editinfos.Add(Info);
                }
            }
            _dbContext.Projects.AddRange(addinfos);
            _dbContext.Projects.UpdateRange(editinfos);
            //_dbContext.Projects.AddRange(projects);
            //await _dbContext.SaveChangesAsync();
            _dbContext.SaveChanges();
            var meta = new
            {
                msg = "任务添加成功",
                status = 200
            };
            //_dbContext.SaveChanges();
            return Json(new { meta, addinfos, editinfos });
        }

        /// <summary>
        /// 批量添加移动计提表
        /// </summary>
        /// <returns></returns>
        [HttpPost("addjitis")]
        public IActionResult AddJitis([FromBody] List<MobileAccrual> jitis)
        //public async Task<IActionResult> AddProjects([FromBody] List<Project> projects)
        {
            // 查出所有信息删除
            var info = _dbContext.MobileAccruals.ToList();
            if (info != null)
            {
                _dbContext.MobileAccruals.RemoveRange(info);
            }
            
            //_dbContext.SaveChanges();
            //要添加的数据列表
            //List<Project> addinfos = new List<Project>();

            //foreach (var project in projects)
            //{
            //    var Info = _dbContext.Projects.Where(s => s.MobileProjectNo == project.MobileProjectNo).FirstOrDefault();
            //    if (Info == null)
            //    {
            //        addinfos.Add(project);
            //    }
            //    else
            //    {
            //        Info.ProjectName = project.ProjectName ?? Info.ProjectName;
            //        Info.Area = project.Area ?? Info.Area;
            //        //Info.SettlementMoney = project.SettlementMoney ?? Info.SettlementMoney;
            //        if (Info.SettlementMoney != project.SettlementMoney)
            //        {
            //            Info.SettlementMoney = project.SettlementMoney;
            //        }
            //        Info.ProjectManager = project.ProjectManager ?? Info.ProjectManager;
            //        Info.ServiceManager = project.ServiceManager ?? Info.ServiceManager;
            //        editinfos.Add(Info);
            //    }
            //}
            _dbContext.MobileAccruals.AddRange(jitis);
            //_dbContext.Projects.UpdateRange(editinfos);
            //_dbContext.Projects.AddRange(projects);
            //await _dbContext.SaveChangesAsync();
            _dbContext.SaveChanges();
            var data = "删除了"+ info.Count() + "条记录，更新了" + jitis.Count() + "条记录";
            var meta = new
            {
                msg = "任务添加成功",
                status = 200
            };
            //_dbContext.SaveChanges();
            return Json(new { meta, data });
        }


        /// <summary>
        /// 添加工程项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("project")]
        public async Task<IActionResult> AddProject([FromBody] Project project)
        {
            //方法二：Using PredicateBuilder
            //LinqKit.Microsoft.EntityFrameworkCore
            //https://github.com/scottksmith95/LINQKit
            //var predicate = PredicateBuilder.New<User>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            //if (!string.IsNullOrEmpty(user.username))
            //{
            //    predicate = predicate.And(p => p.username == user.username);
            //}
            //var count = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID).Count();
            //var data = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID).ToList();
            //var data = PaginatedList<User>.CreatePagingAsync(users, pageIndex, pageSize);
            //var data = _dbContext.Menus.ToList();
            //string teskcode = DateTime.Now.ToString();
            //var task = StrategicTargetTask
            //{
            //    Teskcode = teskcode
            //}
            //strategictargettask.Teskcode = teskcode;
            //string aa = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //project.EntrustTime = DateTime.Parse(project.EntrustTime.ToString());
            //project.CreateTime = DateTime.Parse(project.CreateTime.ToString());
            _dbContext.Projects.Add(project);
            List<Contract> contracts = new List<Contract>();
            
            if (project.EntrustMoney1 != 0)
            {
                Contract contract = new Contract();
                contract.ProjectNo = project.MobileProjectNo;
                contract.Area = project.Area;
                contract.ContractKind = project.Contractsignkind1;
                contract.EntrustMoney = project.EntrustMoney1;
                contract.CostMoney = project.CostMoney1;
                contract.PriceExcludingTax = project.PriceExcludingTax1;
                contract.SettlementMoney = project.SettlementMoney1;
                contract.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax1;
                contract.Tax = project.Tax1;
                contracts.Add(contract);
            }
            if (project.EntrustMoney2 != 0)
            {
                Contract contract = new Contract();
                contract.ProjectNo = project.MobileProjectNo;
                contract.Area = project.Area;
                contract.ContractKind = project.Contractsignkind2;
                contract.EntrustMoney = project.EntrustMoney2;
                contract.CostMoney = project.CostMoney2;
                contract.PriceExcludingTax = project.PriceExcludingTax2;
                contract.SettlementMoney = project.SettlementMoney2;
                contract.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax2;
                contract.Tax = project.Tax2;
                contracts.Add(contract);
            }
            if (project.EntrustMoney3 != 0)
            {
                Contract contract = new Contract();
                contract.ProjectNo = project.MobileProjectNo;
                contract.Area = project.Area;
                contract.ContractKind = project.Contractsignkind3;
                contract.EntrustMoney = project.EntrustMoney3;
                contract.CostMoney = project.CostMoney3;
                contract.PriceExcludingTax = project.PriceExcludingTax3;
                contract.SettlementMoney = project.SettlementMoney3;
                contract.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax3;
                contract.Tax = project.Tax3;
                contracts.Add(contract);
            }
            if (project.EntrustMoney4 != 0)
            {
                Contract contract = new Contract();
                contract.ProjectNo = project.MobileProjectNo;
                contract.Area = project.Area;
                contract.ContractKind = project.Contractsignkind4;
                contract.EntrustMoney = project.EntrustMoney4;
                contract.CostMoney = project.CostMoney4;
                contract.PriceExcludingTax = project.PriceExcludingTax4;
                contract.SettlementMoney = project.SettlementMoney4;
                contract.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax4;
                contract.Tax = project.Tax4;
                contracts.Add(contract);
            }
            if (project.EntrustMoney5 != 0)
            {
                Contract contract = new Contract();
                contract.ProjectNo = project.MobileProjectNo;
                contract.Area = project.Area;
                contract.ContractKind = project.Contractsignkind5;
                contract.EntrustMoney = project.EntrustMoney5;
                contract.CostMoney = project.CostMoney5;
                contract.PriceExcludingTax = project.PriceExcludingTax5;
                contract.SettlementMoney = project.SettlementMoney5;
                contract.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax5;
                contract.Tax = project.Tax5;
                contracts.Add(contract);
            }
            _dbContext.Contracts.AddRange(contracts);
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "任务添加成功",
                status = 200
            };
            //_dbContext.SaveChanges();
            return Json(new { meta, data = project, contracts });
        }

        /// <summary>
        /// 代购代建项目详细信息
        /// </summary>
        /// <param name="id">项目id</param>
        /// <returns></returns>
        [HttpGet("ProjectInfo/{id}")]
        public async Task<ActionResult> GetProjectInfo(int id)
        {
            //var projectInfo = await _dbContext.Projects.FindAsync(id);

            //var projectInfo2 = _dbContext.Fujians.Where(x => x.ProjectID == id);
            //var projectInfo2 = await projectInfo.Include(i => i.Fujians);

            //var projectInfo = await _dbContext.Projects.Where(x=>x.ID == id).Include(i => i.Fujians).OrderBy(o=>o.CreateTime).ToListAsync();
            
            var projectInfo = await _dbContext.Projects.FindAsync(id);
            //新搜索出来的内容自动拼接到上面的projectInfo里
            var dlinfo = await _dbContext.Fujians.Where(x => x.ProjectID == id).OrderBy(o => o.CreateTime).ToListAsync();
            var contractInfo = await _dbContext.Contracts.Where(x => x.ProjectNo == projectInfo.MobileProjectNo).ToListAsync();
            var mobileAccrualInfo = await _dbContext.MobileAccruals.Where(x => x.ProjectNo == projectInfo.MobileProjectNo).ToListAsync();
            //var newprojectInfo = new
            //{
            //    projectInfo,
            //    children= dlinfo
            //};
            //var projectInfo = _dbContext.Projects.Include(i => i.Fujians).Where(x => x.ID == id);
            //var projectInfo = await _dbContext.Projects.Where(x => x.ID == id);
            // .Where(x => x.ID == id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (projectInfo == null)
            {
                return Json(new { meta = meta2 });
            }
            var meta = new
            {
                msg = "任务查询成功",
                status = 200
            };
            return Json(new { meta, data = projectInfo, contractInfo, mobileAccrualInfo });
        }

        /// <summary>
        /// 修改代购代建项目
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="project">特别注意:不需要更新的字段一定要传递为NULL</param>
        /// <returns></returns>
        [HttpPut("projectid/{id}")]
        public async Task<ActionResult> PutProjectInfo(int id, [FromBody] Project project)
        {
            var existInfo = _dbContext.Projects.Find(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}记录" });
            }
            existInfo.Year = project.Year ?? existInfo.Year;
            existInfo.SerialNo = project.SerialNo ?? existInfo.SerialNo;
            existInfo.Area = project.Area ?? existInfo.Area;
            existInfo.ProjectName = project.ProjectName ?? existInfo.ProjectName;
            //---------------------------------
            //由于EntrustMoney（委托金额）float 不能为空，所以不用判断是否为空，可以直接赋值
            //if (project.ToString().Contains("EntrustMoney"))
            //{
            //    existInfo.EntrustMoney = project.EntrustMoney;
            //}
            //var jobj = JObject.Parse(project.ToString());
            //var name = jobj.Property("EntrustMoney") == null ? "" : jobj["EntrustMoney"].ToString();
            //if (name != null)
            //{
            //    existInfo.EntrustMoney = project.EntrustMoney;
            //}
            //float result = project.EntrustMoney;
            //if (result != 0)
            //{
            //    existInfo.EntrustMoney = project.EntrustMoney;
            //}
            existInfo.EntrustMoney = project.EntrustMoney ?? existInfo.EntrustMoney;
            //---------------------------------
            existInfo.CostMoney = project.CostMoney ?? existInfo.CostMoney;
            existInfo.PriceExcludingTax = project.PriceExcludingTax ?? existInfo.PriceExcludingTax;
            existInfo.SettlementMoney = project.SettlementMoney ?? existInfo.SettlementMoney;
            existInfo.SettlementMoneyExcludingTax = project.SettlementMoneyExcludingTax ?? existInfo.SettlementMoneyExcludingTax;
            existInfo.MarkUpRate = project.MarkUpRate ?? existInfo.MarkUpRate;
            existInfo.EntrustTime = project.EntrustTime ?? existInfo.EntrustTime;
            existInfo.InquiryTime = project.InquiryTime ?? existInfo.InquiryTime;
            existInfo.ContractSignTime = project.ContractSignTime ?? existInfo.ContractSignTime; 
            existInfo.FinalInspectionTime = project.FinalInspectionTime ?? existInfo.FinalInspectionTime;
            existInfo.SettlementTime = project.SettlementTime ?? existInfo.SettlementTime;
            existInfo.MaintenanceCycle = project.MaintenanceCycle ?? existInfo.MaintenanceCycle;
            existInfo.ProjectManager = project.ProjectManager ?? existInfo.ProjectManager;
            existInfo.ServiceManager = project.ServiceManager ?? existInfo.ServiceManager;
            existInfo.CurrentStage = project.CurrentStage ?? existInfo.CurrentStage;
            existInfo.Zhousanbeizhu = project.Zhousanbeizhu ?? existInfo.Zhousanbeizhu;
            existInfo.Supplier = project.Supplier ?? existInfo.Supplier;
            existInfo.Contacts = project.Contacts ?? existInfo.Contacts;
            existInfo.IsFinish = project.IsFinish ?? existInfo.IsFinish;
            existInfo.IsMaintain = project.IsMaintain ?? existInfo.IsMaintain;
            existInfo.Beizhu = project.Beizhu ?? existInfo.Beizhu;
            existInfo.Income = project.Income ?? existInfo.Income;
            existInfo.ActuallyIncome = project.ActuallyIncome ?? existInfo.ActuallyIncome;
            existInfo.IncomeTime = project.IncomeTime ?? existInfo.IncomeTime;
            existInfo.OwnerAcceptanceTime = project.OwnerAcceptanceTime ?? existInfo.OwnerAcceptanceTime;
            await _dbContext.SaveChangesAsync();
             var meta = new
            {
                msg = "用户修改成功",
                status = 200
            };
            return Json(new { meta, data = existInfo });
        }

        /// <summary>
        /// 上传项目附件
        /// </summary>
        /// <returns></returns>
        [HttpPost("uploadfiles")]
        //public IActionResult Uploadfiles()
        public async Task<IActionResult> Uploadfiles()
        {
            //var phicyPath = Path.Combine("filedata",
            //                             Request.Form["Year"].ToString(),
            //                             Request.Form["SerialNo"].ToString() + " " + Request.Form["ProjectName"].ToString(),
            //                             Request.Form["FileKind"].ToString());
            //if (Directory.Exists(phicyPath) == false)//如果不存在就创建file文件夹
            //{
            //    Directory.CreateDirectory(phicyPath);
            //}
            //try
            //{
            //    List<Fujian> fileSystemItems = new List<Fujian>();
            //    IFormFileCollection files = Request.Form.Files;
            //    if (files == null || files.Count() < 1) throw new ArgumentException("上传的文件不存在。");
            //    if (files != null && files.Count > 0)
            //    {




            //        foreach (var file in files)
            //        {
            //            //保存上传的文件
            //            if (file.Length > 0)
            //            {
            //                Guid fileId = Guid.NewGuid();
            //                string originFileName = file.FileName;
            //                string fileExtension = Path.GetExtension(originFileName);//文件后缀名
            //                string filenameWithoutExtensione = Path.GetFileNameWithoutExtension(originFileName);//文件名无后缀
            //                string fileVirtualPath = phicyPath;
            //                string fileFullPath = Path.Combine(FilePathHelper.GenerateWWWRootFileFullPath2("wwwroot", fileVirtualPath), originFileName);
            //                if (System.IO.File.Exists(fileFullPath))
            //                {
            //                    originFileName = filenameWithoutExtensione + "(1)" + fileExtension;

            //                }
            //                string newFileName = originFileName;//旧名字和新名字一样
            //                //string newFileName = FilePathHelper.GenerateUniqueFileName(fileExtension);//新唯一文件名
            //                //string fileVirtualPath = FilePathHelper.GenerateFileVirtualPath(virtualDirName: "filedata");
            //                //string fileFullPath = Path.Combine(FilePathHelper.GenerateWWWRootFileFullPath2(Startup.WebHostEnvironment.WebRootPath, fileVirtualPath), originFileName);
            //                using (var stream = new FileStream(fileFullPath, FileMode.Create))
            //                {
            //                    await file.CopyToAsync(stream);
            //                }
            //                //写入数据库的数据
            //                fileSystemItems.Add(new Fujian
            //                {
            //                    FileId = fileId,
            //                    //ProjectID = projectID,
            //                    ProjectID = int.Parse(Request.Form["ProjectID"]),
            //                    FileKind = Request.Form["FileKind"],
            //                    Uploader = Request.Form["Uploader"],
            //                    OriginFileName = originFileName,
            //                    NewFileName = newFileName,
            //                    FileExtension = fileExtension,
            //                    FileVirtualPath = fileVirtualPath,
            //                    FileFullPath = fileFullPath,
            //                    FileSize = file.Length,
            //                    FileType = file.ContentType,
            //                    CreateTime = DateTime.Now,
            //                    OSPlatform = Environment.OSVersion.Platform.ToString(), //RuntimeInformation.OSDescription ,
            //                    FileCode = SecurityHelper.AesEncrypt(fileId.ToString("n")).Replace("/", "^").Replace("%", "$"),
            //                });
            //            }
            //        }
            //        //将上传成功的文件信息保存至数据库
            //        if (fileSystemItems.Count > 0)
            //        {
            //            await _dbContext.Fujians.AddRangeAsync(fileSystemItems.ToArray());
            //            await _dbContext.SaveChangesAsync();
            //        }
            //    }
            //    return Json(new { code = (int)HttpStatusCode.OK, msg = "上传附件成功", data = fileSystemItems, phicyPath });
            //}
            //catch (Exception ex)
            //{
            //    return Json(new { code = (int)HttpStatusCode.InternalServerError, msg = ex.Message });
            //}

            try
            {
                string test = Startup.WebHostEnvironment.WebRootPath;
                string test2 = FilePathHelper.GenerateWWWRootFileFullPath(Startup.WebHostEnvironment.WebRootPath, "123");

                List<Fujian> fileSystemItems = new List<Fujian>();
                IFormFileCollection files = Request.Form.Files;
                if (files == null || files.Count() < 1) throw new ArgumentException("上传的文件不存在。");
                if (files != null && files.Count > 0)
                {
                    foreach (var file in files)
                    {
                        //保存上传的文件
                        if (file.Length > 0)
                        {
                            Guid fileId = Guid.NewGuid();
                            string originFileName = file.FileName;
                            string fileExtension = Path.GetExtension(originFileName);//文件后缀名
                            string newFileName = FilePathHelper.GenerateUniqueFileName(fileExtension);//唯一文件名拼接后缀名
                            string fileVirtualPath = FilePathHelper.GenerateFileVirtualPath(virtualDirName: "filedata");//创建文件虚拟目录路径
                            //创建文件存储路径(包含根目录及文件存储文件夹 )
                            string fileFullPath = Path.Combine(FilePathHelper.GenerateWWWRootFileFullPath(Startup.WebHostEnvironment.WebRootPath, fileVirtualPath), newFileName);
                            using (var stream = new FileStream(fileFullPath, FileMode.Create))
                            {
                                await file.CopyToAsync(stream);
                            }
                            //写入数据库
                            fileSystemItems.Add(new Fujian
                            {
                                FileId = fileId,
                                //ProjectID = projectID,
                                ProjectID = int.Parse(Request.Form["ProjectID"]),
                                FileKind = Request.Form["FileKind"],
                                Uploader = Request.Form["Uploader"],
                                Rid = Request.Form["Rid"],
                                RoleName= Request.Form["RoleName"],
                                OriginFileName = originFileName,
                                NewFileName = newFileName,
                                FileExtension = fileExtension,
                                FileVirtualPath = fileVirtualPath,
                                FileFullPath = fileFullPath,
                                FileSize = file.Length,
                                FileType = file.ContentType,
                                CreateTime = DateTime.Now,
                                OSPlatform = Environment.OSVersion.Platform.ToString(), //RuntimeInformation.OSDescription ,
                                FileCode = SecurityHelper.AesEncrypt(fileId.ToString("n")).Replace("/", "^").Replace("%", "$"),
                            });
                        }
                    }
                    //将上传成功的文件信息保存至数据库
                    if (fileSystemItems.Count > 0)
                    {
                        await _dbContext.Fujians.AddRangeAsync(fileSystemItems.ToArray());
                        await _dbContext.SaveChangesAsync();
                    }
                }
                return Json(new { code = (int)HttpStatusCode.OK, msg = "上传附件成功", data = fileSystemItems, test, test2 });
            }
            catch (Exception ex)
            {
                return Json(new { code = (int)HttpStatusCode.InternalServerError, msg = ex.Message });
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="code">支持fileId、fileCode</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        [Route("downloadfile/{code}")]
        public IActionResult DownloadFile(string code)
        {
            IActionResult result = null;
            try
            {
                Fujian fileItem = ResovleFujian(code);
                result = File(new FileStream(fileItem.FileFullPath, FileMode.Open), fileItem.FileType, fileItem.OriginFileName);
            }
            catch
            //catch (Exception ex)
            {
                result = new StatusCodeResult((int)HttpStatusCode.NotFound);
            }
            return result;
        }

        /// <summary>
        /// 根据code解析fileId、fileCode对应的Fujian
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private Fujian ResovleFujian(string code)
        {
            Fujian fileItem = null;

            //属于guid格式的fileId
            if (Guid.TryParse(code, out Guid guid))
            {
                if (!_dbContext.Fujians.Any(t => t.FileId == guid))
                {
                    throw new ArgumentException($"{guid}文件不存在或已被删除");
                }
                fileItem = _dbContext.Fujians.Find(guid);
            }
            else
            {
                //属于fileId
                string decryptCode = SecurityHelper.AesDecrypt(code.Replace("^", "/").Replace("$", "%"));
                if (string.IsNullOrEmpty(decryptCode))
                {
                    throw new ArgumentException($"无效的文件:{code}");
                }
                else
                {
                    fileItem = _dbContext.Fujians.FirstOrDefault(t => t.FileId == Guid.Parse(decryptCode));
                }
            }
            return fileItem;
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="code">附件filecode或fileid</param>
        /// <param name="fileFullPath"></param>
        /// <returns></returns>
        [HttpDelete("deletefile/{code}/filepath/{fileFullPath}")]
        public async Task<ActionResult> Deletefiles(string code, string fileFullPath)
        {
            var meta = new
            {
                msg = "附件删除成功",
                status = 200
            };
            var meta2 = new
            {
                msg = "文件不存在",
                status = 404
            };
            var meta3 = new
            {
                msg = "code不对",
                status = 404
            };
            //fileFullPath = Server.MapPath(fileFullPath);//相对路径变成完整路径
            if (!System.IO.File.Exists(fileFullPath))//先判断文件是否存在，再执行操作
            {
                return Json(new { meta = meta2 });
            }
            try
            {
                Fujian fileItem = ResovleFujian(code);
                System.IO.File.Delete(fileFullPath);
                _dbContext.Remove(fileItem);
                await _dbContext.SaveChangesAsync();
                return Json(new { meta, data = fileItem });
            }
            catch (Exception)
            {
                //result = new StatusCodeResult((int)HttpStatusCode.NotFound);
                //return new StatusCodeResult((int)HttpStatusCode.NotFound);
                return Json(new { meta = meta3 });
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<IActionResult> Upload()
        {
            try
            {
                List<FileSystemItem> fileSystemItems = new List<FileSystemItem>();
                IFormFileCollection files = Request.Form.Files;
                if (files == null || files.Count() < 1) throw new ArgumentException("上传的文件不存在。");
                if (files != null && files.Count > 0)
                {
                    foreach (var file in files)
                    {
                        //保存上传的文件
                        if (file.Length > 0)
                        {
                            Guid fileId = Guid.NewGuid();
                            string originFileName = file.FileName;
                            string fileExtension = Path.GetExtension(originFileName);
                            string newFileName = FilePathHelper.GenerateUniqueFileName(fileExtension);
                            string fileVirtualPath = FilePathHelper.GenerateFileVirtualPath(virtualDirName: "filedata");
                            string fileFullPath = Path.Combine(FilePathHelper.GenerateWWWRootFileFullPath(Startup.WebHostEnvironment.WebRootPath, fileVirtualPath), newFileName);
                            using (var stream = new FileStream(fileFullPath, FileMode.Create))
                            {
                                await file.CopyToAsync(stream);
                            }
                            fileSystemItems.Add(new FileSystemItem
                            {
                                FileId = fileId,
                                OriginFileName = originFileName,
                                NewFileName = newFileName,
                                FileExtension = fileExtension,
                                FileVirtualPath = fileVirtualPath,
                                FileFullPath = fileFullPath,
                                FileSize = file.Length,
                                FileType = file.ContentType,
                                CreateTime = DateTime.Now,
                                OSPlatform = Environment.OSVersion.Platform.ToString(), //RuntimeInformation.OSDescription ,
                                FileCode = SecurityHelper.AesEncrypt(fileId.ToString("n")).Replace("/", "^").Replace("%", "$"),
                            });
                        }
                    }
                    //将上传成功的文件信息保存至数据库
                    if (fileSystemItems.Count > 0)
                    {
                        await _dbContext.FileSystemItems.AddRangeAsync(fileSystemItems.ToArray());
                        await _dbContext.SaveChangesAsync();
                    }
                }
                return Json(new { code = (int)HttpStatusCode.OK, msg = "上传成功", data = fileSystemItems });
            }
            catch (Exception ex)
            {
                return Json(new { code = (int)HttpStatusCode.InternalServerError, msg = ex.Message });
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="code">支持fileId、fileCode</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        [Route("download/{code}")]
        public IActionResult Download(string code)
        {
            IActionResult result = null;
            try
            {
                FileSystemItem fileItem = ResovleFileSystemItem(code);
                result = File(new FileStream(fileItem.FileFullPath, FileMode.Open), fileItem.FileType, fileItem.OriginFileName);
            }
            catch
            //catch (Exception ex)
            {
                result = new StatusCodeResult((int)HttpStatusCode.NotFound);
            }
            return result;
        }

        /// <summary>
        /// 显示文件
        /// </summary>
        /// <param name="code">支持fileId、fileCode</param>
        /// <returns></returns>
        [HttpGet("view/{code}")]
        public IActionResult Display(string code)
        {
            IActionResult result = null;
            try
            {
                FileSystemItem fileItem = ResovleFileSystemItem(code);
                using (var fs = new FileStream(fileItem.FileFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    result = new FileContentResult(buffer, fileItem.FileType);
                }
            }
            catch
            //catch (Exception ex)
            {
                result = new StatusCodeResult((int)HttpStatusCode.NotFound);
            }
            return result;
        }

        /// <summary>
        /// 根据code解析fileId、fileCode对应的FileSystemItem
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private FileSystemItem ResovleFileSystemItem(string code)
        {
            FileSystemItem fileItem = null;

            //属于guid格式的fileId
            if (Guid.TryParse(code, out Guid guid))
            {
                if (!_dbContext.FileSystemItems.Any(t => t.FileId == guid))
                {
                    throw new ArgumentException($"{guid}文件不存在或已被删除");
                }
                fileItem = _dbContext.FileSystemItems.Find(guid);
            }
            else
            {
                //属于fileId
                string decryptCode = SecurityHelper.AesDecrypt(code.Replace("^", "/").Replace("$", "%"));
                if (string.IsNullOrEmpty(decryptCode))
                {
                    throw new ArgumentException($"无效的文件:{code}");
                }
                else
                {
                    fileItem = _dbContext.FileSystemItems.FirstOrDefault(t => t.FileId == Guid.Parse(decryptCode));
                }
            }
            return fileItem;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="code">附件filecode或fileid</param>
        /// <param name="fileFullPath"></param>
        /// <returns></returns>
        [HttpDelete("file/{code}/filepath/{fileFullPath}")]
        public async Task<ActionResult> Deletefile(string code, string fileFullPath)
        {
            var meta = new
            {
                msg = "附件删除成功",
                status = 200
            };
            var meta2 = new
            {
                msg = "文件不存在",
                status = 404
            };
            var meta3 = new
            {
                msg = "code不对",
                status = 404
            };
            //fileFullPath = Server.MapPath(fileFullPath);//相对路径变成完整路径
            if (!System.IO.File.Exists(fileFullPath))//先判断文件是否存在，再执行操作
            {
                return Json(new { meta = meta2 });
            }
            try
            {
                FileSystemItem fileItem = ResovleFileSystemItem(code);
                System.IO.File.Delete(fileFullPath);
                _dbContext.Remove(fileItem);
                await _dbContext.SaveChangesAsync();
                return Json(new { meta, data = fileItem });
            }
            catch (Exception)
            {
                //result = new StatusCodeResult((int)HttpStatusCode.NotFound);
                //return new StatusCodeResult((int)HttpStatusCode.NotFound);
                return Json(new { meta = meta3 });
            }
        }

//        /// <summary>
//        /// 二级用户获取任务列表
//        /// </summary>
//        /// <param name="title">标题</param>
//        /// <param name="dept">部门</param>
//        /// <param name="pagenum">当前页数</param>
//        /// <param name="pageSize">当前页码</param>
//        /// <returns></returns>
//        [HttpGet("tesksecinfo")]
//        public async Task<IActionResult> GetTesksecInfo([FromQuery] string title, int dept, int pagenum = 1, int pageSize = 20)
//        {
//            //方法二：Using PredicateBuilder
//            //LinqKit.Microsoft.EntityFrameworkCore
//            //https://github.com/scottksmith95/LINQKit
//            //var predicate = PredicateBuilder.New<StrategicTargetOrganization>(true); //Expression<Func<Blog, bool>> predicate = c => true;
//            ////if (!string.IsNullOrEmpty(title))
//            ////{
//            ////    predicate = predicate.And(p => p.Title.Contains(title));
//            ////}
//            //if (dept != 0)
//            //{
//            //    predicate = predicate.And(p => p.Dept == dept);
//            //}
//            //var info = _dbContext.StrategicTargetOrganizations.Where(predicate).Select(s => s).OrderBy(o => o.ID).Include(a=>a.StrategicTargetTask);

//            //var data = await PaginatedList<StrategicTargetOrganization>.CreatePagingAsync(info, pagenum, pageSize);

//            //foreach (var item in info)
//            //{
//            //    var info2 = _dbContext.StrategicTargetTasks
//            //        .Where(a => a.ID == item.StrategicTargetTaskID)
//            //        .Single();
//            //}
//            //var predicate = PredicateBuilder.New<StrategicTargetTask>(true); //Expression<Func<Blog, bool>> predicate = c => true;
//            //if (!string.IsNullOrEmpty(title))
//            //{
//            //    predicate = predicate.And(p => p.Title.Contains(title));
//            //}


//            //方法一
//            //var info = _dbContext.StrategicTargetTasks
//            //    .Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
//            //    .Select(s => s)
//            //    .OrderBy(o => o.ID)
//            //    .Include(a => a.AppraiseUnits);
//            //var game = _dbContext.StrategicTargetTasks.Include(a => a.AppraiseUnits);

//            //var data = await PaginatedList<StrategicTargetOrganization>.CreatePagingAsync(info, pagenum, pageSize);

//            //执行查询SQL语句
//                        var info = _dbContext.SqlQueryDynamic(@"SELECT StrategicTargetOrganizations.ID, StrategicTargetOrganizations.Dept, StrategicTargetOrganizations.Deptmentname, 
//                            StrategicTargetOrganizations.Appraise, StrategicTargetOrganizations.Grade, 
//                            StrategicTargetOrganizations.Gradeself, StrategicTargetOrganizations.Rank, StrategicTargetOrganizations.State, 
//                            StrategicTargetTasks.Title, StrategicTargetTasks.CreateTime,StrategicTargetOrganizations.score1,StrategicTargetOrganizations.score2,StrategicTargetOrganizations.score3,
//                            StrategicTargetOrganizations.filelist1,StrategicTargetOrganizations.filelist2,StrategicTargetOrganizations.filelist3,StrategicTargetOrganizations.bz1,StrategicTargetOrganizations.bz2,StrategicTargetOrganizations.bz3
//            FROM      StrategicTargetOrganizations INNER JOIN
//                            StrategicTargetTasks ON StrategicTargetOrganizations.StrategicTargetTaskID = StrategicTargetTasks.ID where StrategicTargetOrganizations.Dept=@dept order by StrategicTargetOrganizations.ID desc offset ((@pagenum-1)*@pageSize) rows
//fetch next @pageSize rows only",
//                                                                                                       new[]{
//                                                                                                                    new SqlParameter("@dept", dept),
//                                                                                                                    new SqlParameter("@pagenum", pagenum),
//                                                                                                                    new SqlParameter("@pageSize", pageSize)
//                                                                                                           }
//                                                                                                       );
//            //var info2 = await _dbContext.StrategicTargetOrganizations2.Where(a => a.Dept == dept).OrderBy(o => o.ID).Select(s => new
//            //{
//            //    s.Appraise,
//            //    s.CreateTime,
//            //    s.Dept,
//            //    s.Deptmentname,
//            //    s.Grade,
//            //    s.Gradeself,
//            //    s.ID,
//            //    s.Rank,
//            //    s.State,
//            //    s.StrategicTargetTask
//            //}).ToListAsync();
//            //var info = (from StrategicTargetTask in _dbContext.StrategicTargetTasks
//            //            join StrategicTargetOrganization in _dbContext.StrategicTargetOrganizations on StrategicTargetTask.ID equals StrategicTargetOrganization.StrategicTargetTaskID
//            //            //where StrategicTargetOrganization.Dept equals dept
//            //            select new 
//            //            {
//            //                dept = StrategicTargetOrganization.Dept,
//            //                title= StrategicTargetTask.Title
//            //            }).Where(a => a.dept == dept);
//            int count = await _dbContext.StrategicTargetOrganizations.Where(a=>a.Dept== dept).CountAsync();
//            var data = new
//            {
//                pagenum,
//                pageSize,
//                total = count,
//                items = info
//            };

//            var meta = new
//            {
//                msg = "获取任务列表成功",
//                status = 200
//            };
//            return Json(new { meta = meta, data = data });
//        }
//        /// <summary>
//        /// 查询任务sec
//        /// </summary>
//        /// <param name="id">任务id</param>
//        /// <returns></returns>
//        [HttpGet("tesksec/{id}")]
//        public async Task<ActionResult> GetTesksecInfo(int id)
//        {
//            var teskInfo = await _dbContext.StrategicTargetOrganizations.FindAsync(id);
//            var meta2 = new
//            {
//                msg = "Not Found",
//                status = 404
//            };
//            if (teskInfo == null)
//            {
//                return Json(new { meta = meta2 });
//            }
//            string title = string.Empty;
//            if (teskInfo != null)
//            {
//                var teskInfo2 = await _dbContext.StrategicTargetTasks.FindAsync(teskInfo.StrategicTargetTaskID);
//                title = teskInfo2.Title;
//            }
//            var meta = new
//            {
//                msg = "任务sec查询成功",
//                status = 200
//            };
//            return Json(new { meta = meta, data = teskInfo, title = title });
//        }

//        /// <summary>
//        /// 修改任务sec
//        /// </summary>
//        /// <param name="id">任务id</param>
//        /// <param name="strategicTargetOrganization">特别注意:不需要更新的字段一定要传递为NULL</param>
//        /// <returns></returns>
//        [HttpPut("tesksecedit/{id}")]
//        public async Task<ActionResult> PutTesksecInfo(int id, [FromBody] StrategicTargetOrganization strategicTargetOrganization)
//        {
//            var existInfo = _dbContext.StrategicTargetOrganizations.Find(id);
//            var meta2 = new
//            {
//                msg = "Not Found",
//                status = 404
//            };
//            if (existInfo == null)
//            {
//                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}任务记录" });
//            }
//            existInfo.score1 = strategicTargetOrganization.score1;
//            existInfo.score2 = strategicTargetOrganization.score2;
//            existInfo.score3 = strategicTargetOrganization.score3;
//            existInfo.filelist1 = strategicTargetOrganization.filelist1;
//            existInfo.filelist2 = strategicTargetOrganization.filelist2;
//            existInfo.filelist3 = strategicTargetOrganization.filelist3;
//            existInfo.bz1 = strategicTargetOrganization.bz1;
//            existInfo.bz2 = strategicTargetOrganization.bz2;
//            existInfo.bz3 = strategicTargetOrganization.bz3;
//            //existInfo.score1 = strategicTargetOrganization.score1 ?? existInfo.score1;
//            //existInfo.score2 = strategicTargetOrganization.score2 ?? existInfo.score2;
//            //existInfo.score3 = strategicTargetOrganization.score3 ?? existInfo.score3;
//            //existInfo.filelist1 = strategicTargetOrganization.filelist1 ?? existInfo.filelist1;
//            //existInfo.filelist2 = strategicTargetOrganization.filelist2 ?? existInfo.filelist2;
//            //existInfo.filelist3 = strategicTargetOrganization.filelist3 ?? existInfo.filelist3;
//            //existInfo.bz1 = strategicTargetOrganization.bz1 ?? existInfo.bz1;
//            //existInfo.bz2 = strategicTargetOrganization.bz2 ?? existInfo.bz2;
//            //existInfo.bz3 = strategicTargetOrganization.bz3 ?? existInfo.bz3;
//            if (strategicTargetOrganization.State == 2)
//            {
//                existInfo.State = strategicTargetOrganization.State;
//            }
//            //existInfo.State = strategicTargetOrganization.State ?? existInfo.State;
//            await _dbContext.SaveChangesAsync();
//            var meta = new
//            {
//                msg = "任务修改成功",
//                status = 200
//            };
//            return Json(new { meta = meta, data = existInfo });
//        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("roles")]
        public async Task<ActionResult> RoleList()
        {
            //string str = "2,3,4,6,7,9,10,11,12,13,14,15,16,17,18,19,20,22,25,26,31,32,33,34,35,37,38";
            //string str2 = str.Split(",")[0];

            //info两个角色信息
            var Info = await _dbContext.roles
                //.Select(s => new
                //{
                //    s.id,
                //    s.roleDesc,
                //    s.roleName,
                //    //children= One(s.rightid,0)
                //    //children = Rights
                //    //children = _dbContext.Rights
                //    //.Where(w=>w.level=="0" && (w.id==2 || w.id == 3 || w.id == 4 || w.id == 6 || w.id == 7 || w.id == 9))
                //    //.ToList()
                //    rid = s.rightid,
                //    //children = _dbContext.Rights
                //    //.Where(w => w.level == "0")
                //    //.Select(x => new  //匿名类
                //    //{
                //    //    x.id,
                //    //    x.authName,
                //    //    x.level,
                //    //    x.pid,
                //    //    x.path,
                //    //    children = _dbContext.Rights
                //    //    .Where(w => w.pid == x.id)
                //    //    .Select(t => new
                //    //    {
                //    //        t.id,
                //    //        t.authName,
                //    //        t.level,
                //    //        t.pid,
                //    //        t.path,
                //    //        children = _dbContext.Rights.Where(w => w.pid == t.id).ToList()
                //    //    })
                //    //    .ToList()
                //    //})
                //    //.ToList()
                //})
                .ToListAsync();
            //定义一个输出的对象
            object info2 = "";
            //定义一个list对象
            List<object> rlist = new List<object>();
            foreach (var item in Info)
            {
                //item.rightid = item.rightid.Split(",")[0];
                //将2,3,6等id字符串分割成字符串数组
                string[] ids = item.rightid.Split(",");
                //定义一个长度和字符串数组一样的int数组
                int[] idss = new int[item.rightid.Split(",").Count()];
                Right Rightsinfo = new Right();
                //所有权限对象
                List<Right> Rightlist=new List<Right>();
                //for循环字符串数组
                for (int i = 0; i < item.rightid.Split(",").Count(); i++)
                {
                    // 将字符串数组转换成int数组
                    idss[i] = Convert.ToInt32(ids[i]);
                    //查询出id对应的权限信息赋值给Rightsinfo
                    Rightsinfo = _dbContext.Rights.Find(idss[i]);
                        //.Where(w => w.id == int.Parse(item.rightid.Split(",")[i]))
                        //.Where(w => w.id == idss[i]).;

                    Rightlist.Add(Rightsinfo);
                }
                //一级权限对象List
                List<Right> Rightlist2 = new List<Right>();
                Rightlist2 = Rightlist.Where(w => w.level == "0").ToList();
                //二级权限对象List
                List<Right> Rightlist3 = new List<Right>();
                Rightlist3 = Rightlist.Where(w => w.level == "1").ToList();
                //三级权限对象List
                List<Right> Rightlist4 = new List<Right>();
                Rightlist4 = Rightlist.Where(w => w.level == "2").ToList();
                //object rrll = "";
                //foreach (var rl4 in Rightlist4)
                //{
                //    rrll = Rightlist3.Select(s => new
                //    {
                //        s.id,
                //        s.level,
                //        s.path,
                //        s.pid,
                //        children = Rightlist4
                //        .Where(w=>w.id==s.pid)
                //        .Select(s => new
                //        {
                //            s.id,
                //            s.level,
                //            s.path,
                //            s.pid,
                //        })
                //    }).ToList();
                //}
                
                object rrrlll = "";
                //将三级权限json数据根据对应的pid绑定到二级权限，将二级权限json数据根据对应的pid绑定到一级权限
                rrrlll = Rightlist2.Select(s => new
                    {
                        s.id,
                        s.authName,
                        s.level,
                        s.path,
                        s.pid,
                        children = Rightlist3
                        .Where(w => w.pid == s.id)
                        .Select(ss => new
                        {
                            ss.id,
                            ss.authName,
                            ss.level,
                            ss.path,
                            ss.pid,
                            children = Rightlist4
                                .Where(ww => ww.pid == ss.id)
                                .Select(sss => new
                                {
                                    sss.id,
                                    sss.authName,
                                    sss.level,
                                    sss.path,
                                    sss.pid,
                                }).ToList()
                        }).ToList()
                }).ToList();
                //将一级权限json数据绑定到角色json数据
                object rl = new
                {
                    item.id,
                    item.roleName,
                    item.roleDesc,
                    children= rrrlll
                };
                //将完整角色json数据添加到一个新的list里
                rlist.Add(rl);

                //var rl3= Rightlist3.Select(s => new {
                //    s.id,
                //    s.authName,
                //    s.level,
                //    s.pid,
                //    s.path,
                //    children= Rightlist4.Where(r=>r.id== s.pid).ToList()
                //});

                //var rl2 = Rightlist2.Select(s => new {
                //    s.id,
                //    s.authName,
                //    s.level,
                //    s.pid,
                //    s.path,
                //    children = rl3.Where(r => r.id == s.pid).ToList()
                //});

                //info2 = Info.Select(s => new
                //{
                //    s.id,
                //    s.roleName,
                //    s.roleDesc,
                //    children = Rightlist2.Select(s=> new {
                //        s.id,
                //        s.authName,
                //        s.level,
                //        s.pid,
                //        s.path,
                //        children = Rightlist3.Select(s => new {
                //            s.id,
                //            s.authName,
                //            s.level,
                //            s.pid,
                //            s.path,
                //            children = Rightlist4.Where(r => r.id == s.pid)
                //        })
                //    })
                //});
            }


            var meta = new
            {
                msg = "获取角色列表成功",
                status = 200
            };
            return Json(new { meta, data = rlist });
        }
        //public string One(string rightid,int level)
        //{
        //    string[] arr = new string[]{ };
        //    for (int i = 0; i < rightid.Split(',').Count(); i++)
        //    {
        //        arr.Append(rightid.Split(",")[i]);
        //        //arr.Append(_dbContext.Rights.Where(w => w.id == int.Parse(rightid.Split(",")[i])).ToList());
        //    }
        //    return arr.ToString();
        //}
        /// <summary>
        /// 权限列表
        /// </summary>
        /// <param name="type">显示类型，list or tree</param>
        /// <returns></returns>
        [HttpGet("rights/{type}")]
        public async Task<ActionResult> RightList(string type)
        {
            object Info="";
            //var children = _dbContext.Rights.Where(w => w.pid == 2).ToList();
            if (type=="list")
            {
                Info = await _dbContext.Rights.ToListAsync();
            }
            else if (type=="tree")
            {
                Info = await _dbContext.Rights.Where(w => w.level == "0")
                    .Select(x=> new {
                        x.id,
                        x.authName,
                        x.level,
                        x.pid,
                        x.path,
                        children = _dbContext.Rights.Where(w => w.level== "1" && w.pid==x.id)
                        .Select(t=> new {
                            t.id,
                            t.authName,
                            t.level,
                            t.pid,
                            t.path,
                            children = _dbContext.Rights.Where(r => r.level == "2" && r.pid == t.id)
                            .Select(l=> new {
                                l.id,
                                l.authName,
                                l.level,
                                l.pid,
                                l.path
                            }).ToList()
                        }).ToList()
                    }).ToListAsync();
                //Info = await _dbContext.Rights
                //    .Where(w=>w.level=="0")
                //    .Select(x => new  //匿名类
                //    {
                //        x.id,
                //        x.authName,
                //        x.level,
                //        x.pid,
                //        x.path,
                //        children= _dbContext.Rights
                //        .Where(w => w.pid == x.id)
                //        .Select(t=> new
                //        {
                //            t.id,
                //            t.authName,
                //            t.level,
                //            t.pid,
                //            t.path,
                //            children = _dbContext.Rights.Where(w => w.pid == t.id).ToList()
                //        })
                //        .ToList()
                //    })
                //    .ToListAsync();
            }
            var meta = new
            {
                msg = "获取权限列表成功",
                status = 200
            };
            return Json(new { meta, data = Info });
        }

        /// <summary>
        /// 删除单个权限
        /// </summary>
        /// <param name="roleid">角色id</param>
        /// <param name="rightid">角色rightid</param>
        /// <returns></returns>
        [HttpDelete("roles/{roleid}/rights/{rightid}")]
        public async Task<ActionResult> DeleteRight(int roleid, string rightid)
        {
            //查询角色id,判断是否存在
            var existRole = _dbContext.roles.Find(roleid);
            var meta2 = new { msg = "Not Found", status = 404 };
            if (existRole == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的角色Id:{roleid}" });
            }
            //角色id包含的rightid分割循环比对,判断是否存在rightid
            //string[] rightList = existRole.rightid.Split(",");
            List<string> rightList = existRole.rightid.Split(",").ToList();
            //存在的权限
            bool existRight = false;
            int index = 0;
            //---------------新的修改--------------------
            //权限等级
            string lev = "";
            //-----------------------------------
            for (int i = 0; i < rightList.Count(); i++)
            {
                //如果rightid存在rightid列表中
                if (rightList[i] == rightid)
                {
                    existRight = true;
                    index = i;
                    //---------------新的修改--------------------
                    var existRightinfo = _dbContext.Rights.Find(int.Parse(rightid));
                    lev = existRightinfo.level;
                    //-----------------------------------
                }
            }
            
            if (!existRight)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的权限Id:{rightid}" });
            }
            rightList.RemoveAt(index);//利用泛型类remove掉元素
            //---------------新的修改--------------------
            //List<Right> Right3jiinfo2 = new List<Right>();
            //object Right3jiinfo2 = new object();
            string err = "";
            //二级权限list
            List<int> right2jiList = new List<int>();
            if (lev=="1")
            {
                //搜索出所有3极权限，和权限list对照删除
                var Rightinfo = _dbContext.Rights.Where(x => x.level == "2" && x.pid == int.Parse(rightid));
                foreach (var item in Rightinfo)
                {
                    for (int i = 0; i < rightList.Count(); i++)
                    {
                        //如果rightid存在rightid列表中
                        if (rightList[i] == item.id.ToString())
                        {
                            rightList.RemoveAt(i);//利用泛型类remove掉元素
                        }
                    }
                }
            }
            else if (lev == "0")
            {
                //搜索出所有2极权限，和权限list对照删除
                var Right2jiinfo = _dbContext.Rights.Where(x => x.level == "1" && x.pid == int.Parse(rightid));
                foreach (var item in Right2jiinfo)
                {
                    
                    for (int i = 0; i < rightList.Count(); i++)
                    {
                        //如果rightid存在rightid列表中
                        if (rightList[i] == item.id.ToString())
                        {
                            rightList.RemoveAt(i);//利用泛型类remove掉元素
                        }
                    }
                    
                }


                //搜索出所有2级权限
                //var Right2jiinfo2 = _dbContext.Rights.Where(x => x.level == "1" && x.pid == int.Parse(rightid));
                //通过循环搜索出2级权限下面的所有3级权限
                //根据2极权限的id（2极id=3极pid）搜索出相关3极权限
                //foreach (var item5 in Right2jiinfo2)
                //{
                //    var Right3jiinfo = _dbContext.Rights.Where(x => x.level == "2" && x.pid == item5.id);

                //    try
                //    {
                //        foreach (var item3 in Right3jiinfo)
                //        {
                //            for (int i = 0; i < rightList.Count(); i++)
                //            {
                //                //如果rightid存在rightid列表中
                //                if (rightList[i] == item3.id.ToString())
                //                {
                //                    rightList.RemoveAt(i);//利用泛型类remove掉元素
                //                }
                //            }
                //        }
                //    }
                //    catch (Exception e)
                //    {
                //        err = e.ToString();
                //        //throw;
                //    }
                //}
                //var Right3jiinfo = _dbContext.Rights.Where(x => x.level == "2" && x.pid == item.id);
                ////if (Right3jiinfo.Count()!=0)
                ////{
                //try
                //{
                //    foreach (var item3 in Right3jiinfo)
                //    {
                //        for (int i = 0; i < rightList.Count(); i++)
                //        {
                //            //如果rightid存在rightid列表中
                //            if (rightList[i] == item3.id.ToString())
                //            {
                //                rightList.RemoveAt(i);//利用泛型类remove掉元素
                //            }
                //        }
                //    }
                //}
                //catch (Exception e)
                //{
                //    err = e.ToString();
                //    //throw;
                //}

                ////}
            }


            //--------------新的修改---------------------


            //数组转换成string用逗号分隔
            string newarr = string.Join(",", rightList.ToArray());
            //double[] newarr = rightList.ToArray();//再由泛型类转换成数组
            //foreach (var item in rightList)
            //{
            //    if (item== Rightid)
            //    {
            //        existRight = true;
            //    }
            //}


            //定义一个输出的对象
            //object info2 = "";
            //定义一个list对象
            //List<object> rlist = new List<object>();
            
            //将2,3,6等id字符串分割成字符串数组
            string[] ids = newarr.Split(",");
            //定义一个长度和字符串数组一样的int数组
            int[] idss = new int[newarr.Split(",").Count()];
            Right Rightsinfo = new Right();
            //所有权限对象
            List<Right> Rightlist = new List<Right>();
            //for循环字符串数组
            for (int i = 0; i < newarr.Split(",").Count(); i++)
            {
                // 将字符串数组转换成int数组
                idss[i] = Convert.ToInt32(ids[i]);
                //查询出id对应的权限信息赋值给Rightsinfo
                Rightsinfo = _dbContext.Rights.Find(idss[i]);
                //.Where(w => w.id == int.Parse(item.rightid.Split(",")[i]))
                //.Where(w => w.id == idss[i]).;

                Rightlist.Add(Rightsinfo);
            }
            //一级权限对象List
            List<Right> Rightlist2 = new List<Right>();
            Rightlist2 = Rightlist.Where(w => w.level == "0").ToList();
            //二级权限对象List
            List<Right> Rightlist3 = new List<Right>();
            Rightlist3 = Rightlist.Where(w => w.level == "1").ToList();
            //三级权限对象List
            List<Right> Rightlist4 = new List<Right>();
            Rightlist4 = Rightlist.Where(w => w.level == "2").ToList();

            object rrrlll = "";
            //将三级权限json数据根据对应的pid绑定到二级权限，将二级权限json数据根据对应的pid绑定到一级权限
            rrrlll = Rightlist2.Select(s => new
            {
                s.id,
                s.authName,
                s.level,
                s.path,
                s.pid,
                children = Rightlist3
                    .Where(w => w.pid == s.id)
                    .Select(ss => new
                    {
                        ss.id,
                        ss.authName,
                        ss.level,
                        ss.path,
                        ss.pid,
                        children = Rightlist4
                            .Where(ww => ww.pid == ss.id)
                            .Select(sss => new
                            {
                                sss.id,
                                sss.authName,
                                sss.level,
                                sss.path,
                                sss.pid,
                            }).ToList()
                    }).ToList()
            }).ToList();
            //将一级权限json数据绑定到角色json数据
            //object rl = new
            //{
            //    existRole.id,
            //    existRole.roleName,
            //    existRole.roleDesc,
            //    children = rrrlll
            //};
            //将完整角色json数据添加到一个新的list里
            //rlist.Add(rl);



            existRole.rightid = newarr;
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "权限删除成功",
                status = 200
            };
            return Json(new { meta, data = rrrlll});
        }

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <returns></returns>
        [HttpPost("roles/{roleId}/rights")]
        public async Task<IActionResult> Editrights(int roleId,[FromBody] role Role)
        {

            var existInfo = _dbContext.roles.Find(roleId);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的角色Id:{roleId}任务记录" });
            }
            //existInfo.username = user.username ?? existInfo.username;
            //existInfo.mobile = user.mobile ?? existInfo.mobile;
            existInfo.rightid = Role.rightid;
            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "权限修改成功",
                status = 200
            };
            return Json(new { meta, data = existInfo });




            //var existInfo = _dbContext.roles.Find(roleId);
            //var meta2 = new
            //{
            //    msg = "Not Found",
            //    status = 404
            //};
            //if (existInfo == null)
            //{
            //    return Json(new { meta = meta2, msg = $"找不到指定的角色Id:{roleId}记录" });
            //}
            ////existInfo.username = user.username ?? existInfo.username;
            //if (string.IsNullOrEmpty(rids))
            //{
            //    existInfo.rightid = "";
            //}
            //else
            //{
            //    existInfo.rightid = rids;
            //}

            //await _dbContext.SaveChangesAsync();
            //var meta = new
            //{
            //    msg = "权限设置状态修改成功",
            //    status = 200
            //};
            //return Json(new { meta = meta, data = existInfo });
        }

        /// <summary>
        /// 设置角色
        /// </summary>
        /// <returns></returns>
        [HttpPut("users/{userid}/role")]
        public async Task<IActionResult> Editroles(int userid, [FromBody] User user)
        {

            var existInfo = _dbContext.Users.Find(userid);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的角色Id:{userid}任务记录" });
            }
            //existInfo.username = user.username ?? existInfo.username;
            //existInfo.mobile = user.mobile ?? existInfo.mobile;
            existInfo.rid = user.rid;
            var roleinfo = _dbContext.roles.Find(user.rid);
            existInfo.role_name = roleinfo.roleName;

            await _dbContext.SaveChangesAsync();
            var meta = new
            {
                msg = "权限用户角色成功",
                status = 200
            };
            return Json(new { meta, data = existInfo });
        }

        /// <summary>
        /// 部门列表
        /// </summary>
        /// <param name="type">显示类型，list or tree</param>
        /// <returns></returns>
        //[HttpGet("rights/{type}")]
        [HttpGet("departmentslist/{type}")]
        public async Task<ActionResult> DeptList(string type)
        {
            object Info = "";
            if (type == "list")
            {
                Info = await _dbContext.Departments
                    .OrderBy(c => c.departmentId)
                    //.Select(y => new {
                    //    value=y.departmentId,
                    //    leabe=y.departmentName
                    //})
                    .ToArrayAsync();
            }
            else if (type == "tree")
            {

                Info = await _dbContext.Departments
                    .Where(w => w.leve == "1")
                    .Select(x => new  //匿名类
                    {
                        x.ID,
                        x.departmentName,
                        x.leve,
                        x.departmentId,
                        children = _dbContext.Departments
                        .Where(w => w.departmentId.Substring(0,2) == x.departmentId & w.leve == "2")
                        .Select(t => new
                        {
                            t.ID,
                            t.departmentName,
                            t.leve,
                            t.departmentId,
                            children = _dbContext.Departments
                            .Where(w => w.departmentId.Substring(0, 4) == t.departmentId & w.leve == "3")
                            .Select(c => new
                            {
                                c.ID,
                                c.departmentName,
                                c.leve,
                                c.departmentId,
                                children = _dbContext.Departments.Where(w => w.departmentId.Substring(0, 6) == c.departmentId & w.leve == "4").ToList()
                            })
                            .ToList()
                        })
                        .ToList()
                    })
                    .ToListAsync();
            }
            var meta = new
            {
                msg = "获取部门列表成功",
                status = 200
            };
            return Json(new { meta, data = Info });
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <returns></returns>
        //[HttpGet("rights/{type}")]
        [HttpPost("departments")]
        public async Task<ActionResult> Adddept([FromBody] Department department)
        {
            //方法二：Using PredicateBuilder
            //LinqKit.Microsoft.EntityFrameworkCore
            //https://github.com/scottksmith95/LINQKit
            var predicate = PredicateBuilder.New<Department>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            if (!string.IsNullOrEmpty(department.departmentName))
            {
                predicate = predicate.And(p => p.departmentName == department.departmentName);
            }
            var count = _dbContext.Departments.Where(predicate).Select(s => s).OrderBy(o => o.ID).Count();
            //var data = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID).ToList();
            //var data = PaginatedList<User>.CreatePagingAsync(users, pageIndex, pageSize);
            //var data = _dbContext.Menus.ToList();

            var meta = new { msg = "部门添加成功", status = 201 };
            var meta2 = new { msg = "部门已存在", status = 401 };
            if (count == 1)
            {
                return Json(new { meta = meta2 });
            }
            else
            {
                var info = _dbContext.Departments
                    .Where(w => w.departmentId.Contains(department.departmentId) & w.departmentId.Length == department.departmentId.Length + 2)
                    .OrderByDescending(o=>o.departmentId)
                    //.Select(s=>new {
                    //    s.departmentId,
                    //    s.departmentName,
                    //    s.leve
                    //})
                    .FirstOrDefault();
                if (info == null)
                {
                    department.departmentId += "01";
                }
                else
                {
                    string id = info.departmentId;
                    int num=int.Parse(id.Substring(id.Length - 2,2))+1;
                    string strnum = "";
                    if (num<10)
                    {
                        strnum = "0" + num.ToString();
                    }
                    //department.departmentId = info.departmentId[0..^2] + (int.Parse(info.departmentId.Substring(info.departmentId.Length - 2, 2)) + 1).ToString();
                    department.departmentId = info.departmentId[0..^2] + strnum;
                    if (department.departmentId.Length == 4)
                    {
                        department.leve = "2";
                    }
                    else if (department.departmentId.Length == 6)
                    {
                        department.leve = "3";
                    }
                    else if (department.departmentId.Length == 6)
                    {
                        department.leve = "4";
                    }
                }
                _dbContext.Departments.Add(department);
                await _dbContext.SaveChangesAsync();
                return Json(new { meta, data = department });
            };
        }

        /// <summary>
        /// 查询部门
        /// </summary>
        /// <param name="id">部门id</param>
        /// <returns></returns>
        [HttpGet("departments/{id}")]
        public async Task<ActionResult> GetDepartmentsInfo(int id)
        {
            var DepartInfo = await _dbContext.Departments.FindAsync(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (DepartInfo == null)
            {
                return Json(new { meta = meta2 });
            }
            var meta = new
            {
                msg = "部门查询成功",
                status = 200
            };
            return Json(new { meta, data = DepartInfo });
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="id">部门id</param>
        /// <param name="department">特别注意:不需要更新的字段一定要传递为NULL</param>
        /// <returns></returns>
        [HttpPut("departments/{id}")]
        public async Task<ActionResult> EditDepartment(int id, [FromBody] Department department)
        {
            var existInfo = _dbContext.Departments.Find(id);
            var meta2 = new
            {
                msg = "Not Found",
                status = 404
            };
            if (existInfo == null)
            {
                return Json(new { meta = meta2, msg = $"找不到指定的Id:{id}记录" });
            }

            var predicate = PredicateBuilder.New<Department>(true); //Expression<Func<Blog, bool>> predicate = c => true;
            if (!string.IsNullOrEmpty(department.departmentName))
            {
                predicate = predicate.And(p => p.departmentName == department.departmentName);
            }
            var count = _dbContext.Departments.Where(predicate).Select(s => s).OrderBy(o => o.ID).Count();
            var meta3 = new { msg = "部门已存在", status = 401 };
            if (count == 1)
            {
                return Json(new { meta = meta3 });
            }
            else
            {
                existInfo.departmentName = department.departmentName ?? existInfo.departmentName;
                //existInfo.mobile = user.mobile ?? existInfo.mobile;
                //existInfo.email = user.email ?? existInfo.email;
                await _dbContext.SaveChangesAsync();
                var meta = new
                {
                    msg = "部门修改成功",
                    status = 200
                };
                return Json(new { meta, data = existInfo });
            }
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns></returns>
        [HttpGet("test")]
        public IActionResult Test([FromQuery] string title, int dept, int pagenum = 1, int pageSize = 5)
        {
            //方法一
            //var info = _dbContext.Clubs
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id)
            //    .Include(a => a.League);
            //var info = _dbContext.Leagues
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id);
            ////var game = _dbContext.StrategicTargetTasks.Include(a => a.AppraiseUnits);

            //var data = await PaginatedList<League>.CreatePagingAsync(info, pagenum, pageSize);

            var data = _dbContext.Clubs
        .Select(x => new  //匿名类
        {
            x.Id,
            //LeagueName = x.League.Name,

            // x.League,
            x.Players,
            x.Name,
        }).ToList();
                //.Include(i => i.League)
                //.Select(s => new {
                //    s.Name,
                //    //s.League
                //})
                //.ToList()
                //;
            //var data2 = _dbContext.Leagues
            //    .Include(i=>i.Clubs)
            //    //var data2 = _dbContext.Leagues
            //    //.Include(x => x.Clubs)
            //    //.AsNoTracking()
            //    //    .Select(s => new {
            //    //        s.Name,
            //    //        s.Country,
            //    //        s.Clubs
            //    //    })
            //    .ToList();
            var meta = new
            {
                msg = "获取任务列表成功",
                status = 200
            };
            return Json(new { meta, data });
        }

        

        /// <summary>
        /// 测试接口2
        /// </summary>
        /// <returns></returns>
        [HttpGet("test2")]
        public IActionResult Test2([FromQuery] string title, int dept, int pagenum = 1, int pageSize = 5)
        {
            //方法一
            //var info = _dbContext.Clubs
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id)
            //    .Include(a => a.League);
            //var info = _dbContext.Leagues
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id);
            ////var game = _dbContext.StrategicTargetTasks.Include(a => a.AppraiseUnits);

            //var data = await PaginatedList<League>.CreatePagingAsync(info, pagenum, pageSize);


            var data = _dbContext.Leagues
                //.Include(x => x.Clubs)
                .Select(s => new {
                    s.Name,
                    s.Country,
                    s.Clubs
                })
                .ToList();
            var meta = new
            {
                msg = "获取任务列表成功",
                status = 200
            };
            return Json(new { meta, data });
        }

        /// <summary>
        /// 测试接口3
        /// </summary>
        /// <returns></returns>
        [HttpGet("test3")]
        public IActionResult Test3([FromQuery] string title, int dept, int pagenum = 1, int pageSize = 5)
        {
            //方法一
            //var info = _dbContext.Clubs
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id)
            //    .Include(a => a.League);
            //var info = _dbContext.Leagues
            //    //.Where(s => string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //    //.Select(s => s)
            //    .OrderBy(o => o.Id);
            ////var game = _dbContext.StrategicTargetTasks.Include(a => a.AppraiseUnits);

            //var data = await PaginatedList<League>.CreatePagingAsync(info, pagenum, pageSize);
            var data = _dbContext.Clubs.Include(a => a.Players).ToListAsync();
            //.Include(i => i.League)
            //.Select(s => new {
            //    s.Name,
            //    //s.League
            //})
            //.ToList()
            //;
            //var data2 = _dbContext.Leagues
            //    .Include(i=>i.Clubs)
            //    //var data2 = _dbContext.Leagues
            //    //.Include(x => x.Clubs)
            //    //.AsNoTracking()
            //    //    .Select(s => new {
            //    //        s.Name,
            //    //        s.Country,
            //    //        s.Clubs
            //    //    })
            //    .ToList();
            var meta = new
            {
                msg = "获取任务列表成功",
                status = 200
            };
            return Json(new { meta, data });
        }

        ///// <summary>
        ///// 菜单列表
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet("menus")]
        //public IActionResult menus()
        //{
        //    var data = _dbContext.Leagues.ToList();
        //    var data2 = _dbContext.Clubs.ToList();
        //    var data3 = _dbContext.Players.ToList();
        //    return Json(new { code = 200, msg = "ok", Clubs = data2 });
        //}
    }
}
